package com.jvtd.eyl.ui.main.home.read.office;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jvtd.eyl.R;
import com.jvtd.eyl.bean.binding.BookBean;
import com.jvtd.eyl.databinding.FragmentOfficeBinding;
import com.jvtd.eyl.ui.main.home.read.ReadMvpView;
import com.jvtd.eyl.ui.main.home.read.ReadPresenter;
import com.jvtd.eyl.ui.main.home.read.base.ReadBaseFragment;
import com.jvtd.utils.FileUtils;
import com.jvtd.widget.dialog.JvtdAlertDialog;
import com.olivephone.sdk.DocumentView;
import com.olivephone.sdk.DocumentViewController;
import com.olivephone.sdk.DocumentViewFactory;
import com.olivephone.sdk.LicenseData;
import com.olivephone.sdk.LoadListener;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

/**
 * 作者:chenlei
 * 时间:2018/11/27 10:27 AM
 */
public class OfficeFragment extends ReadBaseFragment implements ReadMvpView {
    private static final String TAG = "OfficeFragment";
    @Inject
    ReadPresenter<ReadMvpView> mPresenter;
    private FragmentOfficeBinding mBinding;

    private static final String SELECT_KEY = "SELECT_KEY";
    private BookBean mBookBean;

    //officesdk view
    protected DocumentView mDocumentView;
    protected DocumentViewController mDocumentViewController;

    public static OfficeFragment newInstance(BookBean bookBean) {
        Bundle args = new Bundle();
        args.putParcelable(SELECT_KEY, bookBean);
        OfficeFragment fragment = new OfficeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected View getLayout(LayoutInflater inflater, @Nullable ViewGroup container) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_office, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onDestroyView() {
        mPresenter.onDetach();
        if (mDocumentView != null)
            mDocumentView.destroy();
        mDocumentViewController = null;
        mDocumentView = null;
        super.onDestroyView();
    }

    @Override
    protected void initViewAndData() {
        super.initViewAndData();
        mPresenter.onAttach(this);
        if (getArguments() != null) {
            mBookBean = getArguments().getParcelable(SELECT_KEY);
        }
        if (mBookBean == null) {
            showMessage(R.string.error_message);
            return;
        }

        initOfficeSdk();

        loadFile(mPresenter, mBookBean);
    }

    /**
     * 初始化officesdk
     */
    private void initOfficeSdk() {
        try {
            InputStream in = mContext.getAssets().open("com.jvtd.eyl.lic");
            byte[] licenseData = new byte[1024];
            int licenseDataLength = in.read(licenseData);
            LicenseData.setLicense(licenseData, 0, licenseDataLength);
            in.close();

//            String customWaterMark = "测试版本";
//            /**
//             * CustomWatermarkHelper.setCustomWatermark(String text, int color, float textSize)
//             * 设置用户自定义水印信息
//             * @param text 水印文本信息
//             * @param color 水印文本颜色 默认为android.graphics.Color.RED
//             * @param textSize 水印文本大小 默认大小36
//             */
//            CustomWatermarkHelper.setCustomWatermark(customWaterMark, Color.RED,36);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //初始化界面及控制器
    private void initDocument() {
        Map<String, String> options = new HashMap<>();
        options.put(DocumentViewController.Options.OPTIONS_DEFAULT_SCALE, "0.5");
        options.put(DocumentViewController.Options.OPTIONS_DEFAULT_ENCODING, "UTF-8");
        if (TextUtils.equals(mBookBean.getType(), BookBean.TYPE_DOC) || TextUtils.equals(mBookBean.getType(), BookBean.TYPE_TXT)) {
            mDocumentView = DocumentViewFactory.newWordView(mContext, options);
        } else if (TextUtils.equals(mBookBean.getType(), BookBean.TYPE_XLS)) {
            mDocumentView = DocumentViewFactory.newSpreadsheetView(mContext);
        } else if (TextUtils.equals(mBookBean.getType(), BookBean.TYPE_PPT)) {
            mDocumentView = DocumentViewFactory.newPresentationView(mContext);
        } else if (TextUtils.equals(mBookBean.getType(), BookBean.TYPE_PDF)) {
            mDocumentView = DocumentViewFactory.newPDFView(mContext);
        }
        mDocumentViewController = mDocumentView.getController();
        mDocumentViewController.setPinchZoomEnabled(false);
        if (!TextUtils.equals(mBookBean.getType(), BookBean.TYPE_PDF)) {// PDF In progress
            this.mDocumentViewController.setPageScrollListener(new DocumentViewController.PageScrollListener() {
                @Override
                public void onPageScolled(boolean isFinished) {
                    Log.i(TAG, "Page scrolled. State : " + isFinished);
                }
            });
            this.mDocumentViewController.setPageScaleListener(new DocumentViewController.PageScaleListener() {
                @Override
                public void onPageScaleChanged() {
                    Log.i(TAG, "Page scale changed.");
                }
            });
        }
    }

    //绑定界面
    private void bindViewToContainer() {
        if (mDocumentView == null) return;
        View content = mDocumentView.asView();
        mBinding.officeView.addView(content);
    }

    /**
     * 初始化pdf界面
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    private void initOfficeView() {
        File file = new File(FileUtils.getFilePath(mContext, mBookBean.getUrl(), String.format(".%s", mBookBean.getFileType())));
        // 检查加密并加载文件
        try {
            // 加载文件
            if (mDocumentViewController == null) {
                showMessage(R.string.loading_failed);
                return;
            }
            boolean encrypted = mDocumentViewController.checkEncrypted(new FileInputStream(file), true);
            if (encrypted) {
                inputPassword();
            } else {
                loadOffice(null);
            }
        } catch (IOException e) {
            showMessage(R.string.loading_failed);
        }
    }

    /**
     * 加载pdf
     *
     * @param password pdf密码
     */
    @MainThread
    private void loadOffice(String password) {
        mDocumentViewController.loadFile(password, new LoadListener() {
            @Override
            public void onWrongPassword() {
                if (getActivity() != null)
                    getActivity().runOnUiThread(() -> {
                        //密码错误
                        inputPassword();
                    });
            }

            @Override
            public void onProgressChanged(final int newProgress) {
                if (getActivity() != null)
                    getActivity().runOnUiThread(() -> {
                        //当前进度
                    });
            }

            @Override
            public void onError(String description, final Throwable throwable) {
                Log.e(TAG, description, throwable);
                //加载失败
                if (getActivity() != null)
                    getActivity().runOnUiThread(() -> showMessage(R.string.loading_failed));
            }

            @Override
            public void onDocumentLoaded() {
                if (getActivity() != null)
                    getActivity().runOnUiThread(() -> {
                        loadSuccess();
                        bindViewToContainer();
                    });
            }
        });
    }

    private void loadSuccess() {
        initSuccess();
        mBinding.spinKit.setVisibility(View.GONE);
    }

    /**
     * 下载成功
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void downloadFileSuccess() {
        super.downloadFileSuccess();
        initDocument();
        initOfficeView();
    }

    /**
     * 下载失败
     *
     * @author Chenlei
     * created at 2018/11/15
     **/
    @Override
    public void downloadFileFailed() {
        showMessage(R.string.download_error_tips);
    }

    /**
     * 输入密码
     */
    private void inputPassword() {
        new JvtdAlertDialog().setTitle(getString(R.string.prompt))
                .setEditHint(getString(R.string.please_input_password))
                .setEdit(true)
                .setCanCancelable(false)
                .setKeyBackEnabled(false)
                .setShowContentLayout(true)
                .setOnClickListener((position, inputText) -> {
                    if (position == JvtdAlertDialog.LEFT && getActivity() != null) {
                        getActivity().finish();
                    } else {
                        mBinding.spinKit.setVisibility(View.VISIBLE);
                        loadOffice(inputText);
                    }
                })
                .show(getChildFragmentManager());
    }

//    /**
//     * 根据进度保存
//     *
//     * @author Chenlei
//     * created at 2018/11/15
//     **/
//    @Override
//    public void onPageChanged(int page, int pageCount)
//    {
//        mBookBean.setReadNum(page);
//        updateBook(mBookBean);
//    }
}
